package com.springdemo.tools.jackjson;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

/**
 * json转化对象
 * @author ss
 * @date   2013-10-10 下午05:15:59
 */
public class JackJson {
	public static Logger logger = Logger.getLogger(JackJson.class);
	/** 格式化时间的string */
	@SuppressWarnings("unused")
	private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";



	/**
	 * json转换为java对象
	 * 
	 * <pre>
	 * return JackJson.fromJsonToObject(this.answersJson, JackJson.class);
	 * </pre>
	 * 
	 * @param <T>
	 *            要转换的对象
	 * @param json
	 *            字符串
	 * @param valueType
	 *            对象的class
	 * @return 返回对象
	 */
	public static <T> T fromJsonToObject(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("JsonParseException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}

	/**
	 * java对象转换为json字符串
	 * 
	 * @param object
	 *            Java对象
	 * @return 返回字符串
	 */
	public static String fromObjectToJson(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			String jsonString = mapper.writeValueAsString(object);
			jsonString = jsonString.replace("select * from ( select row_.*, rownum rownum_ from (", "");
			jsonString = jsonString.replace(" ) row_ where rownum <= 0 ) where rownum_ >0", "");
			jsonString = jsonString.replace("limit", "");
			jsonString = jsonString.replace("order by", "");
			//jsonString = jsonString.replace("desc","").replace("asc", "");
			//System.out.println("json========>"+mapper.writeValueAsString(object));
			//return mapper.writeValueAsString(object);
			return jsonString;
		} catch (JsonGenerationException e) {
			logger.error("JsonGenerationException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}

	
}
